package xjay.ai.emotionalsupport.routing;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xjay.ai.emotionalsupport.exception.StrategyNotFoundException;
import xjay.ai.emotionalsupport.routing.strategy.PsychologicalRoutingStrategy;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 对外暴露的情绪路由，包括情绪识别了
 */
@Service
public class StrategyRouter {
    /**
     * <策略名, 策略实例>
     */
    private final Map<String, PsychologicalRoutingStrategy> strategyMap;
    @Resource
    private StrategyContext context;
    @Autowired //Spring会查找所有标记为Bean(即查找所有@Service或@Component)的实现该接口的类，这些类的实例注入到list中
    public StrategyRouter(List<PsychologicalRoutingStrategy> strategies) {
        this.strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        strategy -> strategy.getClass().getName(),
                        strategy -> strategy
                ));

    }



    public String route(String message) {
        String analysis = context.sentimentAnalysis(message); //情绪识别
        for(PsychologicalRoutingStrategy strategy : strategyMap.values()) {
            if(strategy.support(analysis)) { // 该策略适用于上下文
                return strategy.execute(analysis); //返回该策略执行结果：情绪路由
            }
        }
        // 如果没有找到匹配的策略，可以提供一个默认策略
        // 比如默认使用共情策略
        //return strategyMap.get("empathy").execute(context); // 假设 "empathy" 是默认策略
        throw new StrategyNotFoundException("No matched strategy found");
    }
}
